import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:shirne_app/widgets/card_widget.dart';
import '../../models/article_model.dart';
import '../../models/list_result.dart';
import '../../models/product_model.dart';
import '../../utils/api.dart';
import '../../utils/tools.dart';
import '../../widgets/article_widget.dart';
import '../../widgets/product_widget.dart';

import '../../config.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _title = "临风小筑";
  List<dynamic> _banners;
  List<dynamic> _cates;
  ListResult _articles;
  ListResult _products;

  bool _loaded = false;

  Map<String, dynamic> siteinfo;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    if (!_loaded) {
      return Center(child: CircularProgressIndicator());
    }

    var childs = List<Widget>();

    if (_cates != null && _cates.length > 0) {
      childs.add(SizedBox(height: 10));
      childs.add(_CategoryWidget(_cates));
    }

    if (_articles != null && _articles.hasList()) {
      childs.add(SizedBox(height: 10));
      childs.add(_renderArticle());
    }

    if (_products != null && _products.hasList()) {
      childs.add(SizedBox(height: 10));
      childs.add(_renderProduct());
    }

    childs.add(Center(
        heightFactor: 2,
        child: Text(siteinfo != null ? siteinfo['webname'] : ' - ')));

    return CustomScrollView(slivers: [
      SliverAppBar(
        pinned: true,
        expandedHeight: Config.windowPixelWidth * .6,
        title: Text(_title),
        flexibleSpace: FlexibleSpaceBar(
          background: _renderBanner(),
          //titlePadding: EdgeInsets.only(right: 50.0),
          //centerTitle: true,
          collapseMode: CollapseMode.parallax,
        ),
      ),
      SliverList(
        delegate: SliverChildListDelegate(childs),
      ),
    ]);
  }

  _renderBanner() {
    //print(bannerWidth.toString()+'/'+ bannerHeight.toString());
    //if(_banners != null)print(_banners.length);
    return (_banners == null || _banners.length < 1)
        ? Container(
            color: Colors.grey,
          )
        : _BannerWidget(_banners);
  }

  _renderArticle() {
    List<Widget> childs = _articles.lists
        .map((item) =>
            ArticleWidget(ArticleModel.fromJson(item as Map), cols: 2))
        .toList();

    if (childs.length > 0) {
      return Container(
        margin: EdgeInsets.only(top: 10),
        child:Card(
        color: Colors.white,
        child:Wrap(
          spacing: 10,
          runSpacing: 10,
          children: childs,
        ),
        ) ,
      );
    }
  }

  _renderProduct() {
    List<Widget> childs = _products.lists
        .map((item) =>
            ProductWidget(ProductModel.fromJson(item as Map), cols: 2))
        .toList();

    if (childs.length > 0) {
      return Container(
        color: Colors.white,
        padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
        child: Wrap(
          spacing: 10,
          runSpacing: 10,
          children: childs,
        ),
      );
    }
  }

  _loadData() {
    Tools.getSiteinfo().then((result) {
      setState(() {
        siteinfo = result;
      });
    });
    Api.post('common/batch', {
      'product.get_list': {'withsku': 1, 'type': 4, 'pagesize': 4},
      'product.get_cates': {'goods_count': 4, 'withsku': 1},
      'article.get_list': {},
      'advs': {'flag': 'banner'}
    }).then((result) {
      var data = result.data;
      if (data == null) return;
      if (!mounted) return;
      setState(() {
        _banners = data['advs'];
        _cates = data['product.get_cates'];
        _products = ListResult.fromJson(data['product.get_list']);
        _articles = ListResult.fromJson(data['article.get_list']);

        _loaded = true;
      });
    });
  }
}

class _BannerWidget extends StatelessWidget {
  final List _banners;

  const _BannerWidget(this._banners, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var bannerWidth = Config.windowPixelWidth;
    var bannerHeight = Config.windowPixelWidth * .6;

    return Swiper(
      itemWidth: bannerWidth,
      itemHeight: bannerHeight,
      itemBuilder: (context, idx) {
        //print(json.encode(_banners[idx]));
        var item = _banners[idx] as Map<String, dynamic>;
        if (item == null) {
          return Placeholder(
            color: Colors.red,
            strokeWidth: 0,
            fallbackWidth: bannerWidth,
            fallbackHeight: bannerHeight,
          );
        }
        return Stack(
          fit: StackFit.expand,
          children: [
            Image.network(
              Tools.fixImageUrl(item['image']),
              fit: BoxFit.cover,
              width: bannerWidth,
              height: bannerHeight,
            ),
            Align(
              alignment: Alignment.bottomCenter,
              heightFactor: 2,
              child: Text(
                item['title'],
                style: TextStyle(color: Colors.white),
              ),
            )
          ],
        );
      },
      itemCount: _banners.length,
      controller: SwiperController(),
    );
  }
}

class _CategoryWidget extends StatelessWidget {
  final List<dynamic> _cates;

  const _CategoryWidget(this._cates, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double width = (Config.windowPixelWidth-50)/4;

    return CardWidget(
      color: Colors.white,
      child: Wrap(
        children:
            _cates.map((item) => _CategoryItemWidget(item,itemWidth: width,)).toList(),
      ),
    );
  }
}

class _CategoryItemWidget extends StatelessWidget {
  final Map<String, dynamic> _item;
  final double itemWidth;

  const _CategoryItemWidget(this._item, {Key key, this.itemWidth = 100})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var icon = Tools.fixImageUrl(_item['icon']);
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(context, '/product/list',
            arguments: {"category": _item['id']});
      },
      child: Container(
        //height: 80,
        width:itemWidth,
        child: Column(
          children: [
             Padding(
                padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),
                child: ClipOval(
                  child: icon == null
                      ? Icon(Icons.cake)
                      : Image.network(
                          icon,
                          fit: BoxFit.cover,
                        ),
                ),
              ),
            
             Text(
                _item['title'],
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                    decoration: TextDecoration.none),
                maxLines: 2,
              ),
          ],
        ),
      ),
    );
  }
}
